﻿// <copyright file="MainsortReController.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace MesAPI.Controllers.Maintenance
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Kingdee.CDP.WebApi.SDK;
    using MesAPI.Extensions.AuthContext;
    using MesAPI.K3Function;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using PublicData;
    using PublicFunction;
    using PublicModelsAndEntities.Entities.Function;
    using PublicModelsAndEntities.Models.MainsortRecord;
    using XinjeMesProgram.Entities;
    using XinjeMesProgram.Entities.BookInfo;
    using XinjeMesProgram.Entities.Function;
    using XinjeMesProgram.Entities.Maintenance;

    /// <summary>
    /// 分拣.
    /// </summary>
    [ApiController]
    [Authorize]
    public class MainsortReController : ControllerBase
    {
#pragma warning disable SA1000 // Keywords should be spaced correctly
#pragma warning disable CS8601
#pragma warning disable CS8602 // 解引用可能出现空引用。
        private readonly ResponseModel response = new();

        /// <summary>
        /// 获取分拣界面数据列表 .
        /// </summary>
        /// <param name="pageSize">每页记录条数 .</param>
        /// <param name="currentPage">当前页码 .</param>
        /// <param name="oneDimensionalCode">产品序列号（一维码）.</param>
        /// <param name="deliveryNumberIN">快递单号 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/mainsortRe/mainsortRecord")]
        [HttpGet]
        public ResponseModel MainsortRecord(int pageSize, int currentPage, string? oneDimensionalCode, string? deliveryNumberIN)
        {
            using FactoryMesContext factoryMes = new();
            {
                if (AuthContextService.CurrentUser.GroupType != "3" || AuthContextService.CurrentUser.GroupType != "4" || AuthContextService.CurrentUser.GroupType != "5")
                {
                    var info = from v in factoryMes.MainsortRecord
                               where v.State == "1"
                               select new MainsortModel
                               {
                                   ID = v.ID,
                                   SortingSpecialist = v.SortingSpecialist,
                                   State = v.State,
                                   WarehousingDate = v.WarehousingDate,
                                   delivery_nameIn = v.Delivery_NameIn,
                                   delivery_numberIn = v.Delivery_NumberIn,
                                   Name = v.Name,
                                   Consignee = v.Consignee,
                                   contact_information = v.Contact_Information,
                                   receiving_contact = v.Receiving_Contact,
                                   shipping_address = v.Shipping_Address,
                                   one_dimensional_code = v.One_Dimensional_Code,
                                   product_model = v.Product_Model,
                                   product_classification = v.Product_Classification,
                                   Product_Name = v.Product_Name,
                                   productCategory = v.Product_Category,
                                   Guarantee = v.Guarantee,
                                   purchasing_unit = v.Purchasing_Unit,
                                   Salesman = v.Salesman,
                                   delivery_time = v.Delivery_Time,
                                   first_iaddress = v.First_Address,
                                   SortingUserId = v.SortingUserId,
                                   FinalConfirmUserId = v.FinalConfirmUserId,
                                   SortingUserName = XinjeCloudUserQuery.GetUserName(v.SortingUserId),
                                   FinalConfirmUserName = XinjeCloudUserQuery.GetUserName(v.FinalConfirmUserId),
                                   UpdateUserName = XinjeCloudUserQuery.GetUserName(v.UpdateUserId),
                                   SortingDate = v.SortingDate,
                                   assignPersonnel = XinjeCloudUserQuery.GetUserName(v.AssignPersonnelUserId),
                                   AllocationState = v.AllocationState,
                                   customerLevel = v.CustomerLevel,
                               };
                    if (!string.IsNullOrEmpty(oneDimensionalCode))
                    {
                        info = info.Where(x => x.one_dimensional_code.Contains(oneDimensionalCode));
                    }

                    if (!string.IsNullOrEmpty(deliveryNumberIN))
                    {
                        info = info.Where(x => x.delivery_numberIn.Contains(deliveryNumberIN));
                    }

                    int count = info.ToList().Count;
                    this.response.SetData(info.ToList().OrderByDescending(x => x.WarehousingDate).ToList().ListPaged(currentPage, pageSize), count);    // 收货时间排序（降序） 格式:XXXX/XX/XX - XX:XX:XX

                    // this.response.SetData(info.ToList().OrderBy(x => x.Name).ToList().ListPaged(currentPage, pageSize), count);
                    // this.response.SetData(info.ToList().OrderBy(x => x.customerLevel).ToList().ListPaged(currentPage, pageSize), count);  // OrderByDescending 是降序
                }
            }

            return this.response;
        }

        /// <summary>
        /// 输入序列码，获取出厂相关信息 .
        /// </summary>
        /// <param name="one_dimensional_code">序列码 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/registrationE/registration")]
        [HttpGet]
        public ResponseModel Registration(string one_dimensional_code)
        {
            List<RegistrationModel> registrations = new();
            if (!string.IsNullOrEmpty(one_dimensional_code))
            {
                List<MainSortBookModel> mainSortBooks = XinjeBookingInfo.GetMainSortBook(one_dimensional_code);
                List<GetProductType> getProductType = XinjeBookingInfo.GetProduct(one_dimensional_code);
                if (mainSortBooks.Count != 0)
                {
                    foreach (var book in mainSortBooks)
                    {
                        List<object> list = GetK3CloudApi.GetBD_MATERIAL(book.BookingCode, out string msg);
                        RegistrationModel registration = new()
                        {
                            One_dimensional_code = book.BookingBarNo,
                            Product_model = book.BookingType,
                            Product_Name = book.BookingType,
                            Guarantee = XinjeBookingInfo.GetGuaranteeInfo(one_dimensional_code),
                            Purchasing_unit = book.BookingGuest,
                            Salesman = book.BookingSale,
                            First_iaddress = book.BookingToPlace,
                            Delivery_time = book.BookingTime.ToString(),

                            // XinjeBookingInfo.GetProduct(One_dimensional_code)[0].productionName
                            // Product_category = XinjeBookingInfo.GetProductCategory(book.BookingName),
                        };

                        if (msg == "操作成功")
                        {
                            if (list[1] != null)
                            {
                                registration.Product_classification = list[1].ToString();
                            }
                            else
                            {
                                registration.Product_classification = "未知";
                            }

                            if (list[2] != null && !string.IsNullOrEmpty(list[2].ToString()))
                            {
                                registration.Product_DeptName = list[2].ToString();
                                registration.Product_category = list[2].ToString();
                            }
                            else
                            {
                                registration.Product_DeptName = string.Empty;
                                registration.Product_category = string.Empty;
                            }
                        }
                        else
                        {
                            registration.Product_classification = "未知";
                            registration.Product_DeptName = "未知";
                            registration.Product_category = "未知";
                        }

                        registrations.Add(registration);
                    }
                }
                else if (getProductType.Count != 0)
                {
                    // 转换
                    if (getProductType[0].ProductCategory == "数字产品" ||
                        (getProductType[0].ProductCategory == "线缆产品" &&
                        (getProductType[0].Name[..4] != "伺服线缆" ||
                        getProductType[0].Name[..4] != "步进电缆")))
                    {
                        getProductType[0].ProductCategory = "生产二部";
                    }
                    else if (getProductType[0].ProductCategory == "驱动产品" ||
                              getProductType[0].Name[..4] == "伺服线缆" ||
                              getProductType[0].Name[..4] == "步进电缆")
                    {
                        getProductType[0].ProductCategory = "生产三部";
                    }
                    else if (getProductType[0].ProductCategory == "电机产品")
                    {
                        getProductType[0].ProductCategory = "生产四部";
                    }

                    // 赋值
                    RegistrationModel registration = new()
                    {
                        Product_model = getProductType[0].SpecificationAndModel,
                        Guarantee = XinjeBookingInfo.GetGuaranteeInfo(one_dimensional_code),
                        Product_Name = getProductType[0].Name,
                        Product_category = getProductType[0].ProductCategory,
                        Product_classification = getProductType[0].ClassifICation,
                    };

                    // 添加
                    registrations.Add(registration);
                    this.response.SetData(registrations, registrations.Count);
                }
                else
                {
                    this.response.SetError("没有查到当前序列码相关的出厂信息");
                    return this.response;
                }

                this.response.SetData(registrations, registrations.Count);
            }
            else
            {
                this.response.SetError("提供的参数不能为空！");
            }

            return this.response;
        }

        /// <summary>
        /// 查询客户名称，拿到客户代码 .
        /// </summary>
        /// <param name="purchasing_unit">客户名称.</param>
        /// <returns> .</returns>
        [Route("/api/v1/mainsortRe/found")]
        [HttpGet]
        public ResponseModel Found(string? purchasing_unit)
        {
            using (FactoryMesContext factoryMes = new())
            {
                // msg = string.Empty;
                StringBuilder info = new();
                var list = new List<object>();
                try
                {
                    // 读取配置，初始化SDK
                    K3CloudApi client = new();

                    // 业务对象标识
                    string formId = "BD_Customer";

                    // 查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名
                    string fieldKeys = "FNumber,FName";

                    // 请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                    var param = new QueryParam()
                    {
                        FormId = formId,
                        FieldKeys = fieldKeys,
                        FilterString = "FName LIKE '%" + purchasing_unit + "%'",
                    };

                    var result = client.ExecuteBillQuery(param.ToJson());
                    if (result.Count >= 1)
                    {
                        // 对返回结果进行解析和校验，这里使用的是JsonPatch
                        var resultJObject = JArray.Parse(JsonConvert.SerializeObject(result[0]));
                        var queryNode = resultJObject.SelectToken("$..IsSuccess");
                        if (queryNode != null)
                        {
                            var isSuccess = queryNode.Value<Boolean>();
                            info.AppendLine(isSuccess ? "操作成功" : "操作失败");
                        }
                        else
                        {
                            info.AppendLine("操作成功");
                        }
                    }
                    else
                    {
                        info.AppendLine("操作成功");
                    }

                    this.response.SetData(result);
                }
                catch (Exception ex)
                {
                    info.AppendLine(ex.Message);
                    this.response.SetData(list);
                }
            }

            return this.response;

            // msg = Regex.Replace(Info.ToString(), @"[\r\n]", "");  这里是自己创建的通讯表格
            // return list;

            // var info = (from v in context.BookingListInfo
            //            where v.BookingGuest.Contains(Purchasing_unit)
            //            select new MainsortRecordTwoModel
            //             {
            //                Contact_Information = v.BookingCustomerPhone,
            //                Purchasing_unit = v.BookingGuest,
            //            }).Distinct();
        }

        /// <summary>
        /// 根据客户代码查询客户默认地址 .
        /// </summary>
        /// <param name="nameID">客户代码.</param>
        /// <returns> .</returns>
        [Route("/api/v1/registrationE/foundname")]
        [HttpGet]
        public ResponseModel Foundname(string? nameID)
        {// 金蝶发胡单列表API
            using FactoryMesContext context = new();

            // msg = string.Empty;
            StringBuilder info = new();
            List<object> list = new();
            try
            {
                // 读取配置，初始化SDK
                K3CloudApi client = new();

                // 业务对象标识
                string formId = "SAL_DELIVERYNOTICE";

                // 查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名
                string fieldKeys = "FReceiveAddress";

                // 请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                var param = new QueryParam()
                {
                    FormId = formId,
                    FieldKeys = fieldKeys,
                    FilterString = "FCustomerID.FNumber = '" + nameID + "'",    // 查询条件
                };

                // var result = client.ExecuteBillQuery(param.ToJson());
                var result = client.ExecuteBillQuery(param.ToJson()).Last();
                if (result.Count >= 1)
                {
                    // 对返回结果进行解析和校验，这里使用的是JsonPatch
                    var resultJObject = JArray.Parse(JsonConvert.SerializeObject(result));
                    var queryNode = resultJObject.SelectToken("$..IsSuccess");
                    if (queryNode != null)
                    {
                        var isSuccess = queryNode.Value<Boolean>();
                        info.AppendLine(isSuccess ? "操作成功" : "操作失败");
                        list = result;
                    }
                    else
                    {
                        info.AppendLine("操作成功");
                        list = result;
                    }
                }
                else
                {
                    info.AppendLine("此公司未查询到默认地址");
                }
            }
            catch (Exception ex)
            {
                info.AppendLine(ex.Message);
            }

            this.response.SetData(list.ToList());
            return this.response;
        }

        /// <summary>
        /// 保存分拣页面收货数数据.
        /// </summary>
        /// <param name="sortsubmission">需求主体 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/sortsubmissionE/sortsubmission")]
        [HttpPost]
        public ResponseModel Sortsubmission(SortsubmissionModel sortsubmission)
        {
            using (FactoryMesContext context = new())
            {
                var query = context.MainsortRecord.OrderByDescending(x => x.WarehousingDate).FirstOrDefault(x => x.One_Dimensional_Code == sortsubmission.one_dimensional_code);
                if (!string.IsNullOrEmpty(sortsubmission.Id))
                {
                    if (AuthContextService.CurrentUser.GroupType == "2" || (AuthContextService.CurrentUser.GroupType == "3" && AuthContextService.CurrentUser.UserType == XinjeMesProgram.Entities.User.UserType.TertiaryUser))
                    {
                        var info = context.MainsortRecord.FirstOrDefault(x => x.ID == sortsubmission.Id);
                        if (info != null)
                        {
                            // ID = RandomHelper.GetRandomizer(12, true, false, true, true),
                            // info.WarehousingDate = DateTime.Parse(sortsubmission.warehousingDate).ToString("yyyy/MM/dd"); // 收货时间
                            info.SortingSpecialist = AuthContextService.CurrentUser.UserName;
                            info.WarehousingDate = sortsubmission.warehousingDate; // 收货时间
                            info.Delivery_NameIn = sortsubmission.delivery_nameIn; // 收货快递名称
                            info.Delivery_NumberIn = sortsubmission.delivery_numberIn; // 收货快递单号
                            info.Name = sortsubmission.name; // 客户名称（现在实则为购货单位）
                            info.Contact_Information = sortsubmission.contact_information; // 客户联系方式
                            info.Consignee = sortsubmission.consignee;
                            info.Receiving_Contact = sortsubmission.receiving_contact;
                            info.Shipping_Address = sortsubmission.shipping_address;
                            info.One_Dimensional_Code = sortsubmission.one_dimensional_code;
                            info.Product_Model = sortsubmission.product_model;
                            info.Product_Classification = sortsubmission.product_classification;
                            info.Product_Name = sortsubmission.product_Name;
                            info.Product_Category = sortsubmission.product_category;

                            // info.Guarantee = string.IsNullOrEmpty(sortsubmission.Guarantee) ? "保外" : sortsubmission.Guarantee;
                            info.Purchasing_Unit = sortsubmission.purchasing_unit;
                            info.Salesman = sortsubmission.salesman;
                            info.Delivery_Time = sortsubmission.delivery_time;
                            info.First_Address = sortsubmission.first_iaddress;
                            info.FinalConfirmUserId = string.Empty;
                            info.UpdateUserId = AuthContextService.CurrentUser.UserID;
                            info.UpdateTime = DateTime.Now;
                            info.State = "1";
                            info.AllocationState = "0";
                            info.CustomerLevel = sortsubmission.customerLevel; // 客户等级
                            context.SaveChanges();
                        }
                        else
                        {
                            this.response.SetError("没找到该分拣单");
                        }
                    }
                    else
                    {
                        this.response.SetError("当前用户不允许编辑");
                    }
                }
                else if (query == null || query.State == "8")
                {
                    MainsortRecordModel mainsortRecord = new()
                    {
                        // WarehousingDate = sortsubmission.warehousingDate,
                        // WarehousingDate = DateTime.Parse(sortsubmission.warehousingDate ?? DateTime.Now.ToString("yyyy/MM/dd")).ToString("yyyy/MM/dd"),
                        ID = RandomHelper.GetRandomizer(12, true, false, true, true),
                        SortingSpecialist = AuthContextService.CurrentUser.UserName,
                        WarehousingDate = sortsubmission.warehousingDate,
                        Delivery_NameIn = sortsubmission.delivery_nameIn,
                        Delivery_NumberIn = sortsubmission.delivery_numberIn,
                        Name = sortsubmission.name,
                        Contact_Information = sortsubmission.contact_information,
                        Consignee = sortsubmission.consignee,
                        Receiving_Contact = sortsubmission.receiving_contact,
                        Shipping_Address = sortsubmission.shipping_address,
                        One_Dimensional_Code = sortsubmission.one_dimensional_code,
                        Product_Model = sortsubmission.product_model,
                        Product_Classification = sortsubmission.product_classification,
                        Product_Name = sortsubmission.product_Name,
                        Product_Category = sortsubmission.product_category,
                        Guarantee = sortsubmission.guarantee,
                        Purchasing_Unit = sortsubmission.purchasing_unit,
                        Salesman = sortsubmission.salesman,
                        Delivery_Time = sortsubmission.delivery_time,
                        First_Address = sortsubmission.first_iaddress,
                        SortingUserId = AuthContextService.CurrentUser.UserID,
                        FinalConfirmUserId = string.Empty,
                        UpdateUserId = string.Empty,
                        SortingDate = DateTime.Now,
                        State = "1",
                        AllocationState = "0",
                        CustomerLevel = sortsubmission.customerLevel, // 客户等级
                        CheckUserId = string.Empty,
                    };
                    context.MainsortRecord.Add(mainsortRecord);
                    context.SaveChanges();
                }
                else
                {
                    this.response.SetError("数据重复录入，请重新确认！");
                }
            }

            return this.response;
        }

        /// <summary>
        /// 分拣页面收货快数据 ID 提交给后端核对页面 .
        /// </summary>
        /// <param name="id">唯一 id .</param>
        /// <returns> .</returns>
        [Route("/api/v1/checkdataE/checkdata")]
        [HttpGet]
        public ResponseModel Checkdata(string id)
        {
            using (FactoryMesContext context = new())
            {
                var info1 = context.MainsortRecord.FirstOrDefault(x => x.ID == id);
                if (info1 != null)
                {
                    info1.State = "2";
                    info1.FinalConfirmUserId = AuthContextService.CurrentUser.UserID;
                    info1.FinalConfirmTime = DateTime.Now;
                    info1.AllocationState = "0";
                    int two = context.MainsortRecord.Count(x => x.One_Dimensional_Code == info1.One_Dimensional_Code);
                    if (two > 1)
                    {
                        info1.SecondaryRepairsOr = "是";
                    }

                    var info2 = context.MaterialTracking3.Where(x => x.SerialNumber == info1.One_Dimensional_Code).FirstOrDefault();
                    if (info2 != null)
                    {
                        info2.State = 1;
                    }

                    context.SaveChanges();
                }
                else
                {
                    this.response.SetError("未查到相关信息");
                }
            }

            return this.response;
        }

        /*/// <summary>
        /// 编辑分拣数据 .
        /// </summary>
        /// <param name="mainSortEdit">需求主体 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/mainsortedit/mainsorteditinfo")]
        [HttpPost]
        public ResponseModel Edit(MainSortEditModel mainSortEdit)
        {
            if (AuthContextService.CurrentUser.GroupType == "2")
            {
                using (FactoryMesContext context = new FactoryMesContext())
                {

                    var info = context.MainsortRecord.FirstOrDefault(x => x.ID == mainSortEdit.Id);
                    if (info != null)
                    {
                    }
                    else
                    {
                        this.response.SetError("没找到该分拣单");
                    }
                }
            }
            else
            {
                this.response.SetError("当前用户不允许编辑");
            }

            return this.response;
        }*/

        /// <summary>
        /// 分拣数据删除 .
        /// </summary>
        /// <param name="id">需求主体 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/error/error1")]
        [HttpPost]

        public ResponseModel EditCost(string? id)
        {
            using (FactoryMesContext context = new())
            {
                var info = context.MainsortRecord.FirstOrDefault(x => x.ID == id);
                if (info != null)
                {
                    string sQL = string.Format("DELETE FROM MainsortRecord WHERE ID = '{0}';select a.ID  from MainsortRecord a  where a.ID='{0}'", id);  // 先删除，再查找
                    _ = context.Deletedata.FromSqlRaw(sQL).ToList();  // 执行SQL
                }
                else
                {
                    this.response.SetError("没找到此数据");
                }
            }

            return this.response;
        }

        /// <summary>
        /// 客户信息添加保存.
        /// </summary>
        /// <param name="data">需求主体.</param>
        /// <returns>.</returns>
        [Route("/api/v1/registrationE/dianhua_increase")]
        [HttpPost]
        public ResponseModel Dianhuaincrease(Customsos data)
        {
            if (AuthContextService.CurrentUser.UserType == XinjeMesProgram.Entities.User.UserType.FourLevelUser && AuthContextService.CurrentUser.GroupType == "2")
            {
                this.response.SetError("组员没有编辑的权限");
                return this.response;
            }
            else
            {
                using FactoryMesContext context = new();
                var query = context.Customs.FirstOrDefault(x => x.ID == data.id);

                if (query != null)
                {
                    query.CustomerLevel = data.customerLevel;
                    query.Name = data.name;
                    query.Shipping_address = data.shipping_address;
                    query.Jishuyuandianhua = data.jishuyuandianhua;
                    query.Contact_information = data.contact_information;
                    context.SaveChanges();
                }
                else
                {
                    Customs customs = new()
                    {
                        ID = RandomHelper.GetRandomizer(12, true, false, true, true),
                        Contact_information = data.contact_information,
                        Name = data.name,
                        CustomerLevel = data.customerLevel,
                        Jishuyuandianhua = data.jishuyuandianhua,
                        Shipping_address = data.shipping_address,
                    };
                    context.Customs.Add(customs);
                    context.SaveChanges();
                }
            }

            return this.response;
        }

        /// <summary>
        /// 客户信息查看 .
        /// </summary>
        /// <param name="name">客户名称 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/registrationE/dianhua_data")]
        [HttpGet]
        public ResponseModel Dianhua_data(string? name)
        {
            using var context = new FactoryMesContext();
            var query = from c in context.Customs
                        select new Customs
                        {
                            ID = c.ID,
                            Contact_information = c.Contact_information,
                            Name = c.Name,
                            CustomerLevel = c.CustomerLevel,
                            Jishuyuandianhua = c.Jishuyuandianhua,
                            Shipping_address = c.Shipping_address,
                        };

            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(x => x.Name.Contains(name));
            }

            List<Customs> result = query.ToList();
            int count = query.Count();
            this.response.SetData(result, count);
            return this.response;
        }

        /// <summary>
        /// 客户信息删除 .
        /// </summary>
        /// <param name="id">ID .</param>
        /// <returns> .</returns>
        [Route("/api/v1/registrationE/dianhua_delete")]
        [HttpGet]
        public ResponseModel Dianhua_delete(string id)
        {
            using var context = new FactoryMesContext();
            var repair = context.Customs.Where(x => x.ID == id).ToList();
            if (repair != null)
            {
                string sQL = string.Format("DELETE FROM Customs WHERE ID = '{0}';select a.ID  from Customs a  where a.ID='{0}'", id);  // 先删除，再查找
                _ = context.Deletedata.FromSqlRaw(sQL).ToList();  // 执行SQL
            }
            else
            {
                this.response.SetError("没找到此数据");
            }

            this.response.SetSuccess("删除成功");

            return this.response;
        }
    }
}
